package com.tomowork.dao.impl;

import com.tomowork.dao.IUserDAO;
import com.tomowork.entity.User;
import com.tomowork.entity.dto.UserDto;
import org.springframework.stereotype.Repository;


import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Repository
public class UserDAOImpl implements IUserDAO {
    @PersistenceContext
    private EntityManager entityManager ;
    @Override
    public User selectByUsernameAndPwd(String username) {
        String jpql = "from User u where u.username=?" ;
        Query query = entityManager.createQuery(jpql);
        query.setParameter(0,username) ;
        User user = null ;
        try {
            user = (User) query.getSingleResult();
        }catch (NoResultException e){
            //todo 知道这里存在异常，但是可以不进行处理
        }
        return user;
    }

    @Override
    public boolean insert(User user) {
        User merge = entityManager.merge(user);
        return merge!=null ;
    }

    @Override
    public boolean selectByUsername(String username) {
        String jpql = "SELECT COUNT(1) FROM User WHERE username = ?" ;
        Query query = entityManager.createQuery(jpql);
        query.setParameter(0,username) ;
        long count = (long) query.getSingleResult();
        return count==1;
    }
}
